package top.ezzz.config;

import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.noear.solon.core.util.MultiMap;
import org.noear.solon.rx.Completable;
import org.noear.solon.rx.handle.RxContext;
import org.noear.solon.rx.handle.RxFilter;
import org.noear.solon.rx.handle.RxFilterChain;

import java.io.IOException;
import java.util.Collection;

@Slf4j
@Component
public class SolonAiFilter implements Filter, RxFilter {

    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        try {
            if ("/".equals(ctx.pathNew())
                    || "/static".equals(ctx.pathNew())
                    || "/dist".equals(ctx.pathNew())) {
                ctx.pathNew(ctx.pathNew() + "/index.html");
            }
            String method = ctx.method();
            String url = ctx.url();
            MultiMap<String> keyValues = ctx.paramMap();
            String body = ctx.body();
            // 打印请求信息
            log.info("请求方法: {}，请求路径 {}, 请求参数: {} ,请求体: {} ", method, url, keyValues, body);
            chain.doFilter(ctx);
            // 打印响应信息
            log.info("响应状态: {}", ctx.status());
            ctx.headerNamesOfResponse().forEach(headerName -> log.info("响应头: {} = {}", headerName, ctx.headerOfResponse(headerName)));
            String output = ctx.attr("output");
            log.info("响应体: {}", output);
            log.info("---------------------------------");
        } catch (Throwable ex) {
            log.error(ex.getMessage(), ex);
        }
    }

    @Override
    public Completable doFilter(RxContext context, RxFilterChain chain) {
        Context ctx = context.toContext();
        try {
            log.info("请求方法: {}，请求路径 {}, 请求参数: {} ,请求体: {} , 响应状态: {}",
                    ctx.method(), ctx.url(), ctx.paramMap(), ctx.body(), ctx.status());
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return chain.doFilter(context).doOnError(err -> log.error(err.getMessage(), err));
    }
}